package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangjun
 * 2019/7/6
 * 23:22
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    @Reference
    private SpuService spuService;
    @Reference
    private CategoryService categoryService;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${pagePath}")
    private String pagePath;

    @GetMapping("/createPage")
    public void createPage(String spuId) {
        //查询商品信息
        Goods goods = spuService.findgoodsById(spuId);
        //获取spu
        Spu spu = goods.getSpu();
        //获取sku列表
        List<Sku> skuList = goods.getSkuList();
        //查询商品分类
        List<String> categoryList = new ArrayList<String>();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());//一级标题
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());//二级标题
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());//三级标题

        //sku地址列表
        Map<String,String> urlMap=new HashMap<String, String>();
        for(Sku sku:skuList){
            if("1".equals(sku.getStatus())){
                String specJson = JSON.toJSONString( JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson,sku.getId()+".html");
            }
        }
        //创建页面 每个spu一个页面
        for (Sku sku : skuList) {
            //上下文
            Context context = new Context();
            //创建模型
            Map<String, Object> dataModel = new HashMap<String, Object>();
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryList", categoryList);
            dataModel.put("skuImages", sku.getImages().split(","));//sku的图片列表
            dataModel.put("spuImages", spu.getImages().split(","));//spu的图片列表
            Map pareItems = JSON.parseObject(spu.getParaItems());//参数列表
            dataModel.put("paraitems", pareItems);
            Map specItems = JSON.parseObject(sku.getSpec());//规格列表
            dataModel.put("specItems",specItems);
            //{"颜色":["金色","黑色","蓝色"],"内存":["6GB+64GB","8GB+128GB,"8GB+256GB]}
           // Map specMap =JSON.parseObject(spu.getSpecItems());//规格核规格选项
            Map<String,List> specMap = (Map)JSON.parseObject(spu.getSpecItems());
            for (String key : specMap.keySet()) {//循环规格
                List<String> list = specMap.get(key);//["金色","黑色","蓝色"]
                List<Map> mapList=new ArrayList<Map>();//新集合
                //循环规格选项
                for(String value:list){
                    Map map=new HashMap();
                    map.put("option",value);//规格选项
                    if( value.equals(specItems.get(key))) {
                        map.put("checked", true);//是否选中
                    }else {
                        map.put("checked", false);//是否选中
                    }
                    Map<String,String>  spec= (Map)JSON.parseObject(sku.getSpec()) ;//当前的Sku
                    spec.put(key,value);
                    String specJson = JSON.toJSONString(spec , SerializerFeature.MapSortField);
                    map.put("url",urlMap.get(specJson));
                    mapList.add(map);
                }
                specMap.put(key,mapList);//新的替换

            }
            dataModel.put("specMap",specMap);

            context.setVariables(dataModel);
            //准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File dest = new File(dir, sku.getId() + ".html");
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
                System.out.println("生成页面" + sku.getId() + ".html");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }


    }
}
